package com.rickpan.controller;

import com.rickpan.common.ApiResponse;
import com.rickpan.service.EncryptionService;
import com.rickpan.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 团队加密管理控制器
 * 
 * @author RickPan Team
 * @version 1.0
 * @since 2025-07-19
 */
@Slf4j
@RestController
@RequestMapping("/api/teams")
@Tag(name = "团队加密管理", description = "团队消息加密密钥管理接口")
public class TeamEncryptionController {

    @Autowired
    private EncryptionService encryptionService;

    /**
     * 获取团队加密密钥
     *
     * @param teamId 团队ID
     * @return 加密密钥响应
     */
    @GetMapping("/{teamId}/encryption-key")
    @Operation(summary = "获取团队加密密钥", description = "获取指定团队的加密密钥，用于消息加密解密")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getTeamEncryptionKey(
            @Parameter(description = "团队ID", required = true) @PathVariable Long teamId) {

        try {
            // 1. 获取当前用户ID
            Long userId = SecurityUtils.getCurrentUserId();
            if (userId == null) {
                return ResponseEntity.status(401)
                    .body(ApiResponse.unauthorized("未授权访问"));
            }
            
            // 2. 确保团队有可用密钥
            if (!encryptionService.ensureTeamKey(teamId, userId)) {
                return ResponseEntity.status(500)
                    .body(ApiResponse.error("团队密钥初始化失败"));
            }
            
            // 3. 获取团队密钥
            String teamKey = encryptionService.getTeamKey(teamId, userId);
            
            // 4. 构建响应数据
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("teamKey", teamKey);
            responseData.put("algorithm", "AES-256-GCM");
            responseData.put("keyLength", 256);
            
            log.info("✅ 团队密钥获取成功: teamId={}, userId={}", teamId, userId);
            
            return ResponseEntity.ok(ApiResponse.success("获取团队密钥成功", responseData));
            
        } catch (SecurityException e) {
            log.warn("⚠️ 团队密钥访问权限不足: teamId={}, error={}", teamId, e.getMessage());
            return ResponseEntity.status(403)
                .body(ApiResponse.forbidden("无权限访问团队密钥"));

        } catch (Exception e) {
            log.error("❌ 获取团队密钥失败: teamId={}", teamId, e);
            return ResponseEntity.status(500)
                .body(ApiResponse.error("获取团队密钥失败: " + e.getMessage()));
        }
    }

    /**
     * 轮换团队密钥
     *
     * @param teamId 团队ID
     * @return 轮换结果
     */
    @PostMapping("/{teamId}/rotate-key")
    @Operation(summary = "轮换团队密钥", description = "生成新的团队加密密钥，旧密钥将失效")
    public ResponseEntity<ApiResponse<Map<String, Object>>> rotateTeamKey(
            @Parameter(description = "团队ID", required = true) @PathVariable Long teamId) {

        try {
            // 1. 获取当前用户ID
            Long userId = SecurityUtils.getCurrentUserId();
            if (userId == null) {
                return ResponseEntity.status(401)
                    .body(ApiResponse.unauthorized("未授权访问"));
            }
            
            // 2. 轮换密钥
            Long newKeyId = encryptionService.rotateTeamKey(teamId, userId);
            
            // 3. 获取新密钥
            String newTeamKey = encryptionService.getTeamKey(teamId, userId);
            
            // 4. 构建响应数据
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("keyId", newKeyId);
            responseData.put("teamKey", newTeamKey);
            responseData.put("algorithm", "AES-256-GCM");
            responseData.put("rotatedAt", System.currentTimeMillis());
            
            log.info("✅ 团队密钥轮换成功: teamId={}, userId={}, newKeyId={}", teamId, userId, newKeyId);
            
            return ResponseEntity.ok(ApiResponse.success("团队密钥轮换成功", responseData));
            
        } catch (SecurityException e) {
            log.warn("⚠️ 团队密钥轮换权限不足: teamId={}, error={}", teamId, e.getMessage());
            return ResponseEntity.status(403)
                .body(ApiResponse.forbidden("无权限轮换团队密钥"));

        } catch (Exception e) {
            log.error("❌ 轮换团队密钥失败: teamId={}", teamId, e);
            return ResponseEntity.status(500)
                .body(ApiResponse.error("轮换团队密钥失败: " + e.getMessage()));
        }
    }

    /**
     * 检查加密服务健康状态
     * 
     * @return 健康状态
     */
    @GetMapping("/encryption/health")
    @Operation(summary = "检查加密服务健康状态", description = "检查加密服务是否正常工作")
    public ResponseEntity<ApiResponse<Map<String, Object>>> checkEncryptionHealth() {
        
        try {
            boolean isHealthy = encryptionService.isHealthy();
            
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("healthy", isHealthy);
            responseData.put("algorithm", "AES-256-GCM");
            responseData.put("checkTime", System.currentTimeMillis());
            
            if (isHealthy) {
                log.debug("✅ 加密服务健康检查通过");
                return ResponseEntity.ok(ApiResponse.success("加密服务正常", responseData));
            } else {
                log.error("❌ 加密服务健康检查失败");
                return ResponseEntity.status(500)
                    .body(ApiResponse.error("加密服务异常"));
            }

        } catch (Exception e) {
            log.error("❌ 加密服务健康检查异常", e);

            return ResponseEntity.status(500)
                .body(ApiResponse.error("加密服务健康检查异常: " + e.getMessage()));
        }
    }

    /**
     * 生成团队密钥（管理员接口）
     *
     * @param teamId 团队ID
     * @return 生成结果
     */
    @PostMapping("/{teamId}/generate-key")
    @Operation(summary = "生成团队密钥", description = "为团队生成新的加密密钥（管理员操作）")
    public ResponseEntity<ApiResponse<Map<String, Object>>> generateTeamKey(
            @Parameter(description = "团队ID", required = true) @PathVariable Long teamId) {

        try {
            // 1. 获取当前用户ID
            Long userId = SecurityUtils.getCurrentUserId();
            if (userId == null) {
                return ResponseEntity.status(401)
                    .body(ApiResponse.unauthorized("未授权访问"));
            }
            
            // 2. 生成密钥
            Long keyId = encryptionService.generateTeamKey(teamId, userId);
            
            // 3. 获取生成的密钥
            String teamKey = encryptionService.getTeamKey(teamId, userId);
            
            // 4. 构建响应数据
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("keyId", keyId);
            responseData.put("teamKey", teamKey);
            responseData.put("algorithm", "AES-256-GCM");
            responseData.put("generatedAt", System.currentTimeMillis());
            
            log.info("✅ 团队密钥生成成功: teamId={}, userId={}, keyId={}", teamId, userId, keyId);
            
            return ResponseEntity.ok(ApiResponse.success("团队密钥生成成功", responseData));
            
        } catch (SecurityException e) {
            log.warn("⚠️ 团队密钥生成权限不足: teamId={}, error={}", teamId, e.getMessage());
            return ResponseEntity.status(403)
                .body(ApiResponse.forbidden("无权限生成团队密钥"));

        } catch (Exception e) {
            log.error("❌ 生成团队密钥失败: teamId={}", teamId, e);
            return ResponseEntity.status(500)
                .body(ApiResponse.error("生成团队密钥失败: " + e.getMessage()));
        }
    }
}
